package jsyf.oa.service.report.newAppReport;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.report.newAppReport.NewAppReportForBRMDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.system.MessageEntity;
import jsyf.oa.entity.system.MessageReceiverEntity;
import jsyf.oa.facade.report.newAppReport.NewAppReportForBRMFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;

@SuppressWarnings("all")
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class NewAppReportForBRMService implements NewAppReportForBRMFacade {

    @Autowired
    private NewAppReportForBRMDao newAppReportForBRMDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;

    /*获取个人*/
    @Override
    public JSONObject getIntentCustomerListForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String nowTime = "";
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            nowTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            nowTime = dateTime.substring(0, 7);
        }
        List<JSONObject> records = newAppReportForBRMDao.getForPersonalIntentCustomerList(userId);
        JSONObject result = new JSONObject();
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getTodaySignForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        String userIds = getRegionManagerByUserId(userId, regionId, true);
        List<JSONObject> jsonObject = new ArrayList<JSONObject>();

        //获取个人考勤信息,判断出勤、缺勤、请假
        List<JSONObject> signToday = newAppReportForBRMDao.getSignAndLeaveForToday(userIds, dateTime);
        if (null != signToday && signToday.size() > 0) {
            for (int i = 0; i < signToday.size(); i++) {
                //1签到/2缺勤/0请假
                JSONObject result = new JSONObject();
                String signCreateTime = signToday.get(i).getString("signCreateTime");
                String beginTime = signToday.get(i).getString("beginTime");
                if (StringUtils.isBlank(signCreateTime) && StringUtils.isBlank(beginTime)) {
                    JSONObject userObject = new JSONObject();
                    userObject.put("userName", userDao.getById(signToday.get(i).getString("userId")).getName());
                    result.put("signState", "2");
                    result.put("result", userObject);
                    jsonObject.add(result);
                }
                if (StringUtils.isNotEmpty(signCreateTime) && StringUtils.isBlank(beginTime)) {
                    result.put("signState", "1");
                    result.put("result", signToday.get(i));
                    jsonObject.add(result);
                }
                if (StringUtils.isNotEmpty(beginTime) && StringUtils.isBlank(signCreateTime)) {
                    result.put("signState", "0");
                    result.put("result", signToday.get(i));
                    jsonObject.add(result);
                }

            }
        }
        JSONObject result = new JSONObject();
        result.put("records", jsonObject);
        return result;
    }

    @Override
    public JSONObject getCostByUserIdAndDateTimeForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        String userIds = getRegionManagerByUserId(userId, regionId, false);
        List<JSONObject> personalCostList = newAppReportForBRMDao.getForPersonalCostByUserIdAndDateTime(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", personalCostList);
        return result;
    }

    @Override
    public JSONObject daQuVisit(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String userIds = getRegionManagerByUserId(userId, "", false);
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        List<JSONObject> userIdList = newAppReportForBRMDao.getUserIdForregionId(userIds, "");
        String newUserIds = "";
        if (null != userIdList && userIdList.size() > 0) {
            for (int i = 0; i < userIdList.size(); i++) {
                newUserIds += "'" + userIdList.get(i).getString("userId") + "',";
            }
        }
        if (!StringUtils.isBlank(newUserIds) && newUserIds.endsWith(",")) {
            userIds = newUserIds.substring(0, newUserIds.length() - 1);
        }
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }

        List<JSONObject> personalCostList = newAppReportForBRMDao.daQuVisit(userIds, dateTime, userId, regionId);
        JSONObject result = new JSONObject();
        result.put("records", personalCostList);
        return result;
    }

    @Override
    public JSONObject daQuVisitByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        StringBuffer condition = new StringBuffer();
        condition.append("and (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL  LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> personalCostList = newAppReportForBRMDao.daQuVisitByUserId(userId, dateTime, condition, requestPage, pageSize);

        int recordCount = newAppReportForBRMDao.daQuVisitByUserIdPageCount(userId, dateTime, condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", personalCostList);
        objResult.put("pager", objPager);
        return objResult;


    }

    @Override
    public JSONObject getCostListByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        String userIds = getRegionManagerByUserId(userId, regionId, false);

        List<JSONObject> personalCostList = newAppReportForBRMDao.getCostListByUserId(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", personalCostList);
        return result;
    }

    @Override
    public JSONObject getVisitByUserIdAndDateTimeForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");//0-电/1-面
        String status = jsonParams.getString("status");//0-AM/1-PM
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);

        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        String userIds = getRegionManagerByUserId(userId, regionId, false);

        List<JSONObject> jsonObjects = newAppReportForBRMDao.getForPersonalDayByUserIdAndDateTime(userIds, dateTime, Integer.valueOf(type), Integer.valueOf(status));
        JSONObject result = new JSONObject();
        result.put("records", jsonObjects);
        return result;
    }

    @Override
    public JSONObject getTodayPlanByUserIdAndDateTimeForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        String userIds = checkDao.getChilderByUserId(userId, true);
        List<JSONObject> tomorrowVisitList = newAppReportForBRMDao.getTomorrowVisitToday(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", tomorrowVisitList);
        return result;
    }

    @Override
    public JSONObject getTodayFirstVisitAndSignForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        String userIds = getRegionManagerByUserId(userId, regionId, false);
        List<JSONObject> firstVisitAndSignList = newAppReportForBRMDao.getFirstVisitAndSignForToday(userIds, dateTime);
        JSONObject result = new JSONObject();
        result.put("records", firstVisitAndSignList);
        return result;
    }

    @Override
    public JSONObject getVisitCustomerByUserIdAndDateTimeForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");//0-电/1-面
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        String userIds = getRegionManagerByUserId(userId, regionId, false);

        List<JSONObject> visitCustomerList = newAppReportForBRMDao.getVisitCustomerByuserIdAndDateTime(userIds, dateTime, Integer.parseInt(type), userId, regionId);
        JSONObject result = new JSONObject();
        result.put("records", visitCustomerList);
        return result;
    }

    @Override
    public JSONObject getCustomerNumByUserIdAndDateTimeForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        String userIds = getRegionManagerByUserId(userId, regionId, false);
        String newUserIds = "";
        if (!StringUtils.isBlank(userIds) && userIds.length() > 1) {
            String[] stringArray = userIds.split(",");
            if (null != stringArray && stringArray.length > 0) {
                for (int i = 0; i < stringArray.length; i++) {
                    String oldUserId = stringArray[i];
                    if (!oldUserId.equals("'" + userId + "'")) {
                        newUserIds += oldUserId + ",";
                    }
                }
            }
        }
        if (!StringUtils.isBlank(newUserIds) && newUserIds.endsWith(",")) {
            userIds = newUserIds.substring(0, newUserIds.length() - 1);
        }
        List<JSONObject> customerNums = newAppReportForBRMDao.getCustomerNumByuserIdAndDateTime(userIds, dateTime);


        JSONObject result = new JSONObject();
        result.put("records", customerNums);
        return result;
    }

    @Override
    public JSONObject getWechatShareListForBRM(String jsonData) {
        JSONObject jsonObject = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonObject.getString("dateTime");
        String userId = jsonObject.getString("userId");
        String regionId = "";
        if (jsonObject.containsKey("regionId")) {
            regionId = jsonObject.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        String userIds = getRegionManagerByUserId(userId, regionId, false);

        String yesterday = DateUtils.getyesterdayByDateTime(dateTime);
        String beforeYesterday = DateUtils.getyesterdayByDateTime(yesterday);

        List<JSONObject> contactsList = newAppReportForBRMDao.getContactsByUserId(userIds, yesterday, beforeYesterday);

        dateTime = dateTime.substring(0, 7);

        String companyId = "";
        JSONObject userObject = userDao.getViewJSONById(userId);
        if (null != userObject) {
            companyId = userObject.getString("companyId");
        } else {
            companyId = "''";
        }
        List<JSONObject> wechatList = newAppReportForBRMDao.getForDepartBycompanyId(dateTime, companyId, userIds);

        getWechatContact(contactsList, wechatList);


        JSONObject result = new JSONObject();
        result.put("records", wechatList);
        return result;
    }

    @Override
    public JSONObject getSaleForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        List<JSONObject> list = new ArrayList<>();
        Map<String, JSONObject> intentCustomers = new HashMap<>();
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        String month = "";
        if (dateTime.substring(5, 7).startsWith("0")) {
            month = dateTime.substring(6);
        } else {
            month = dateTime.substring(5, 7);
        }
        String userIds = getRegionManagerByUserId(userId, regionId, false);

        //大区经理销售报表
        List<JSONObject> listBigManagerList = newAppReportForBRMDao.getNewSaleBigManagerList(userId, dateTime, month);//大区经理
        String newUserIds = "";
        if (!StringUtils.isBlank(userIds) && userIds.length() > 1) {
            String[] stringArray = userIds.split(",");
            if (null != stringArray && stringArray.length > 0) {
                for (int i = 0; i < stringArray.length; i++) {
                    String oldUserId = stringArray[i];
                    if (!oldUserId.equals("'" + userId + "'")) {
                        newUserIds += oldUserId + ",";
                    }
                }
            }
        }
        if (!StringUtils.isBlank(newUserIds) && newUserIds.endsWith(",")) {
            userIds = newUserIds.substring(0, newUserIds.length() - 1);
        }
        //区域经理销售报表
        List<JSONObject> listManagerList = newAppReportForBRMDao.getNewSaleManagerList(userIds, dateTime);//区域经理
        list = listBigManagerList;
        list.addAll(listManagerList);
        //意向客户数量（区域经理）
        List<JSONObject> userIntentCustomer = newAppReportForBRMDao.getIntentCustomerListByUserId(userIds, dateTime);
        if (null != userIntentCustomer && userIntentCustomer.size() > 0) {
            for (int i = 0; i < userIntentCustomer.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                JSONObject userIdAndMW = userIntentCustomer.get(i);
                jsonObject.put("moreThanOneMonth", userIdAndMW.getString("moreThanOneMonth"));
                jsonObject.put("withinOneMonth", userIdAndMW.getString("withinOneMonth"));
                intentCustomers.put(userIdAndMW.getString("userId"), jsonObject);
            }
        }

        for (int i = 0; i < list.size(); i++) {
            String needUserId = list.get(i).getString("userId");
            JSONObject userIntentCustomers = intentCustomers.get(needUserId);
            if (null == userIntentCustomers) {
                list.get(i).put("moreThanOneMonth", 0);
                list.get(i).put("withinOneMonth", 0);
            } else {
                list.get(i).put("moreThanOneMonth", userIntentCustomers.getString("moreThanOneMonth"));
                list.get(i).put("withinOneMonth", userIntentCustomers.getString("withinOneMonth"));
            }
        }

        //排序  公司 -> 大区 -> 岗位 -> 人名
        Comparator<JSONObject> comparator = new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject jsonObject1, JSONObject jsonObject2) {
                if (null == jsonObject1 || null == jsonObject2) {
                    return 123456789;
                }
                if (!jsonObject1.getString("companySortNo").equals(jsonObject2.getString("companySortNo"))) {
                    int sortNo1 = Integer.parseInt(jsonObject1.getString("companySortNo"));
                    int sortNo2 = Integer.parseInt(jsonObject2.getString("companySortNo"));
                    return (sortNo1 - sortNo2) * 10 + 1;
                } else {
                    if (!jsonObject1.getString("regionSortNo").equals(jsonObject2.getString("regionSortNo"))) {
                        int sortNo1 = Integer.parseInt(jsonObject1.getString("regionSortNo"));
                        int sortNo2 = Integer.parseInt(jsonObject2.getString("regionSortNo"));
                        return (sortNo1 - sortNo2) * 200 + 10;
                    } else {
                        if (!jsonObject1.getString("roleNameSortNo").equals(jsonObject2.getString("roleNameSortNo"))) {
                            int sortNo1 = Integer.parseInt(jsonObject1.getString("roleNameSortNo"));
                            int sortNo2 = Integer.parseInt(jsonObject2.getString("roleNameSortNo"));
                            return (sortNo1 - sortNo2) * 4000 + 100;
                        } else {
                            if (!jsonObject1.getString("userName").equals(jsonObject2.getString("userName"))) {
                                int sortNo = jsonObject1.getString("roleNameSortNo").compareTo(jsonObject2.getString("roleNameSortNo"));
                                return sortNo * 80000 + 1000;
                            } else {
                                return 1600000 + 2222;
                            }
                        }
                    }
                }
            }
        };
        Collections.sort(list, comparator);


        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    private String getRegionManagerByUserId(String userId, String regionId, Boolean flag) {
        String userIdList = "";
        String userIds = checkDao.getChilderByUserId(userId, true);
        if (flag) {
            String resignationUserId = checkDao.getResignationByUserIdFroBRM(userId, true);
            if (!"''".equals(resignationUserId)) {
                userIds += "," + resignationUserId;
            }
        }
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        List<JSONObject> userIdsList = newAppReportForBRMDao.getRegionManagerByUserId(userIds, dateTime, regionId);
        if (null != userIdsList && userIdsList.size() > 0) {
            for (int i = 0; i < userIdsList.size(); i++) {
                userIdList += "'" + userIdsList.get(i).getString("userId") + "',";
            }
        } else {
            userIdList = "'',";
        }
        return userIdList = userIdList.substring(0, userIdList.length() - 1);
    }

    @Override
    public JSONObject getTeamBuildingForBRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        String todayMoney = "";
        JSONObject bonusObject = newAppReportForBRMDao.getBonusTodayMoneyByUserId(dateTime, userId);
        if (null == bonusObject) {
            todayMoney = "0";
        } else {
            todayMoney = bonusObject.getString("todayMoney");
        }
        dateTime = dateTime.substring(0, 7);

        List<JSONObject> list = newAppReportForBRMDao.getForGroupVacantAndFine(dateTime, userId);
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).put("todayMoney", todayMoney);
            }
        }
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getVisitPeopleByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String dateTime = jsonParams.getString("dateTime");
        String type = jsonParams.getString("type");
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }

        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        StringBuffer condition = new StringBuffer();
        condition.append("and (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL  LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> list = newAppReportForBRMDao.getVisitPeopleByUserIdAndDateTime(userId, dateTime, type, condition, requestPage, pageSize);


        int recordCount = newAppReportForBRMDao.getVisitPeoplePageCount(userId, dateTime, type, condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", list);
        objResult.put("pager", objPager);
        return objResult;

    }

    private void getWechatContact(List<JSONObject> contactsList, List<JSONObject> wechatList) {
        Map<String, JSONObject> contactsMap = new HashMap<>();
        if (null != contactsList && contactsList.size() > 0) {
            for (int i = 0; i < contactsList.size(); i++) {
                JSONObject userContacts = contactsList.get(i);
                contactsMap.put(userContacts.getString("userId"), userContacts);
            }
        }


        if (null != wechatList && wechatList.size() > 0) {
            for (int i = 0; i < wechatList.size(); i++) {
                JSONObject wechat = wechatList.get(i);
                JSONObject wechatContacts = contactsMap.get(wechat.getString("userId"));
                int num = Integer.parseInt(wechatContacts.getString("num"));
                int contacts = Integer.parseInt(wechatContacts.getString("contacts"));
                wechat.put("num", num);
                wechat.put("contacts", contacts);
            }
        }

    }

    @Override
    public JSONObject getFinishByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        Boolean brm = false;
        List<JSONObject> user = userDao.getViewByUserId(" AND ID=? ", new Object[]{userId});
        if (null != user && user.size() > 0) {
            for (int i = 0; i < user.size(); i++) {
                String roleName = user.get(i).getString("roleName");
                if ("大区经理".equals(roleName) || "区域组长".equals(roleName)) {
                    brm = true;
                    break;
                }
            }
        }
        if (brm) {
            userId = getRegionManagerByUserId(userId, "", false);
        } else {
            userId = "'" + userId + "'";
        }
        List<JSONObject> records = new ArrayList<>();
        if (!StringUtils.isBlank(userId) && userId.length() > 3) {
            String[] stringArray = userId.split(",");
            if (null != stringArray && stringArray.length > 0) {
                for (int i = 0; i < stringArray.length; i++) {
                    JSONObject assessmentDateTimes = newAppReportForBRMDao.getRegionAchivementsByUserIdAndDateTime(stringArray[i], dateTime);
                    String assessmentTime = null;
                    if (null != assessmentDateTimes) {
                        String beginMonth = assessmentDateTimes.getString("beginMonth");
                        String middleMonth = assessmentDateTimes.getString("middleMonth");
                        String endMonth = assessmentDateTimes.getString("endMonth");
                        if (stringArray.length == 1) {
                            assessmentTime = "'" + beginMonth + "'," + "'" + middleMonth + "'," + "'" + endMonth + "'";
                        } else {
                            assessmentTime = "'" + dateTime + "'";
                        }
                        List<JSONObject> customerNums = newAppReportForBRMDao.getFinishByUserIdAndDateTime(stringArray[i], assessmentTime);
                        records.addAll(customerNums);
                    }
                }
            }
        }
        JSONObject result = new JSONObject();
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getForPersonalByUserIdAndDateTime(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);

        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");
        JSONObject User = userDao.getViewJSONById(userId);
        String companyId = User.getString("companyId");

        Calendar c = Calendar.getInstance();
        if (StringUtils.isBlank(dateTime)) {

            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");

        } else {
            dateTime = dateTime.substring(0, 7);
        }
        String today = DateUtils.parse(c.getTime(), "yyyy-MM-dd");

        List<JSONObject> list = newAppReportForBRMDao.getWechatShareList(userId, dateTime, companyId, today, Integer.parseInt(type));


        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getAllCustomerForRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        StringBuffer condition = new StringBuffer();
        condition.append("HAVING (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> allCustomer = newAppReportForBRMDao.getAllCustomerForRM(userId, condition, requestPage, pageSize);
        int recordCount = newAppReportForBRMDao.getAllCustomerPageCount(userId, condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", allCustomer);
        objResult.put("pager", objPager);
        return objResult;

    }

    @Override
    public JSONObject getNewCustomerForRM(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String key = "";
        if (jsonParams.containsKey("key")) {
            key = jsonParams.getString("key");
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        StringBuffer condition = new StringBuffer();
        condition.append("AND (t_wrt_customer.`NAME` LIKE  '%" + key + "%'\n" +
                "OR t_wrt_customer. TEL LIKE '%" + key + "%'\n" +
                "OR t_wrt_customer.`WECHAT` LIKE '%" + key + "%'\n" +
                ")\n");
        List<JSONObject> newCustomer = newAppReportForBRMDao.getNewCustomerForRM(userId, dateTime, condition, requestPage, pageSize);
        int recordCount = newAppReportForBRMDao.getNewCustomerPageCount(userId, dateTime, condition);

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", newCustomer);
        objResult.put("pager", objPager);
        return objResult;


    }

    @Override
    public JSONObject getIntentCustomerForMonth(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("pageSize"))) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (!com.alibaba.dubbo.common.utils.StringUtils.isBlank(jsonParams.getString("requestPage"))) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        List<JSONObject> list = newAppReportForBRMDao.getIntentCustomerForMonth(userId, dateTime, Integer.parseInt(type), requestPage, pageSize);

        int recordCount = newAppReportForBRMDao.getIntentCustomerForMonthPageCount(userId, dateTime, Integer.parseInt(type));

        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        JSONObject objPager = new JSONObject();
        objPager.put("recordCount", recordCount);
        objPager.put("pageCount", pageCount);
        //返回
        JSONObject objResult = new JSONObject();
        objResult.put("records", list);
        objResult.put("pager", objPager);
        return objResult;

    }

    @Override
    public JSONObject getSalesAwardAmount(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String type = jsonParams.getString("type");

        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM");
        } else {
            dateTime = dateTime.substring(0, 7);
        }
        List<JSONObject> list = newAppReportForBRMDao.getSalesAwardAmount(userId, dateTime, Integer.parseInt(type));

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    @Override
    public Boolean getTodayPlanRemind() {
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and roleName='大区经理' " +
                "and jobState!=1 ", new Object[]{});
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        for (int i = 0; i < userList.size(); i++) {
            JSONObject user = userList.get(i);
            //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(user.getString("id"));
            messageEntity.setCreateTime(userDao.getCurrentTime());
            messageEntity.setContent("今日计划");
            messageEntity.setMessageType(3);
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/reportForm/newReportForm/daQuTodayPlanApp.html?&userId=" + user.getString("id") + "&dateTime=" + dateTime + "&msg=0");
            messageEntity.setOpenTitle(String.format(TODAY_PLAN_MESSAGE));
            messageDao.add(messageEntity);
            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(user.getString("id"));
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发送企业微信
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", messageEntity.getCreateUserId());
            msgObject.put("content", String.format(TODAY_PLAN_MESSAGE_WE,
                    "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }


        return true;
    }

    @Override
    public Boolean firstVisitRemind() {
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and roleName='大区经理' " +
                "and jobState!=1 ", new Object[]{});
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        for (int i = 0; i < userList.size(); i++) {
            JSONObject user = userList.get(i);
            //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(user.getString("id"));
            messageEntity.setCreateTime(userDao.getCurrentTime());
            messageEntity.setContent("首次面访");
            messageEntity.setMessageType(3);
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/reportForm/newReportForm/daQuMapApp.html?userId=" + user.getString("id") + "&dateTime=" + dateTime + "&msg=0");
            messageEntity.setOpenTitle(String.format(FIRST_VISIT_MESSAGE));
            messageDao.add(messageEntity);
            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(user.getString("id"));
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发送企业微信
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", messageEntity.getCreateUserId());
            msgObject.put("content", String.format(FIRST_VISIT_MESSAGE_WE,
                    "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        return true;
    }

    @Override
    public Boolean amVisitRemind() {
        List<JSONObject> userList = userDao.getViewJSONListByCondition(" and main=1 and roleName='大区经理' " +
                "and jobState!=1 ", new Object[]{});
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        for (int i = 0; i < userList.size(); i++) {
            JSONObject user = userList.get(i);
            //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(user.getString("id"));
            messageEntity.setCreateTime(userDao.getCurrentTime());
            messageEntity.setContent("上午面访");
            messageEntity.setMessageType(3);
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/reportForm/newReportForm/daQuVisitApp.html?userId=" + user.getString("id") + "&dateTime=" + dateTime + "&msg=0");
            messageEntity.setOpenTitle(String.format(AM_VISIT_MESSAGE));
            messageDao.add(messageEntity);
            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(user.getString("id"));
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发送企业微信
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", messageEntity.getCreateUserId());
            msgObject.put("content", String.format(AM_VISIT_MESSAGE_WE,
                    "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl() + "&receiverId=" + messageReceiverEntity.getId()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }

        return true;
    }

    @Override
    public JSONObject getEmailByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String dateTime = jsonParams.getString("dateTime");
        String userId = jsonParams.getString("userId");
        String realUserId = userId;
        String regionId = "";
        if (jsonParams.containsKey("regionId")) {
            regionId = jsonParams.getString("regionId");
        }
        userId = getUserIdForCompany(userId, regionId, true);
        if (StringUtils.isBlank(dateTime)) {
            Calendar c = Calendar.getInstance();
            dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        }
        dateTime = DateUtils.getyesterdayByDateTime(dateTime);
        String userIds = getRegionManagerByUserId(userId, regionId, false);
        List<JSONObject> userIdsList = newAppReportForBRMDao.getRegionManagerByUserIds(userIds, null);
        String userIdList = "";

        if (null != userIdsList && userIdsList.size() > 0) {
            for (int i = 0; i < userIdsList.size(); i++) {
                userIdList += "'" + userIdsList.get(i).getString("userId") + "',";
            }
        } else {
            userIdList = "'',";
        }
        if (!StringUtils.isBlank(userIdList) && userIdList.endsWith(",")) {
            userIds = userIdList.substring(0, userIdList.length() - 1);

        }
        List<JSONObject> list = newAppReportForBRMDao.getEmailByUserId(userIds, dateTime, userId, realUserId, regionId);
        for (int i = 0; i < list.size(); i++) {
            JSONObject object = list.get(i);
            String readerId = object.getString("readerId");
            if (StringUtils.isBlank(readerId)) {
                if ("未发送".equals(object.getString("titleSend"))) {
                    Integer count = newAppReportForBRMDao.getSendEmail(object.getString("userId"), dateTime);
                    if (null != count && count != 0) {
                        object.put("titleSend", "已发送");
                    }
                }
            }
        }

        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;

    }

    @Override
    public JSONObject regionAndCompanyByUserId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String userId = jsonParams.getString("userId");
        String companyIds = "";
        List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
        if (null != userList && userList.size() > 0) {
            for (int i = 0; i < userList.size(); i++) {
                String selectCompanyId = userList.get(i).getString("companyId");
                String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                //如果有下级
                if (!StringUtils.isBlank(ids)) {
                    //如果有多个下级
                    if (ids.indexOf(",") >= 0) {
                        String[] idsSplit = ids.split(",");
                        for (String id : idsSplit) {
                            companyIds += "'" + id + "',";
                        }
                    } else {
                        //如果只有一个下级
                        companyIds += "'" + ids + "',";
                    }
                }
                companyIds += "'" + selectCompanyId + "',";
            }
            companyIds = companyIds.substring(0, companyIds.length() - 1);
        } else {
            companyIds = "''";
        }
        List<JSONObject> jsonObjects = newAppReportForBRMDao.regionAndCompanyByUserId(userId, companyIds);
        JSONObject result = new JSONObject();
        result.put("records", JSON.toJSON(jsonObjects));
        return result;
    }

    private String getUserIdForCompany(String userId, String regionId, Boolean oneFlag) {
        String userIds = checkDao.getChilderByUserId(userId, false);
        if (!StringUtils.isBlank(regionId)) {
            List<JSONObject> userIdList = newAppReportForBRMDao.getUserIdForregionId(userIds, regionId);
            String newUserIds = "";
            if (null != userIdList && userIdList.size() > 0) {
                if (!oneFlag) {
                    for (int i = 0; i < userIdList.size(); i++) {
                        newUserIds += "'" + userIdList.get(i).getString("userId") + "',";
                    }
                } else {
                    return userIdList.get(0).getString("userId");
                }
            } else {
                return userId;
            }

            if (!StringUtils.isBlank(newUserIds) && newUserIds.endsWith(",")) {
                newUserIds = newUserIds.substring(0, newUserIds.length() - 1);
            }
            return newUserIds;
        } else {
            return userId;
        }
    }
}
